package com.yj_app.qualitytest.fragment;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatSpinner;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.hu_sir.sweet_dialog_reversion.SweetAlertDialog;
import com.rengwuxian.materialedittext.MaterialAutoCompleteTextView;
import com.rengwuxian.materialedittext.MaterialEditText;
import com.yj_app.qualitytest.R;
import com.yj_app.qualitytest.adapter.ArrayAdapter;
import com.yj_app.qualitytest.adapter.HDadapter;
import com.yj_app.qualitytest.base.BaseFragment;
import com.yj_app.qualitytest.common.Config;
import com.yj_app.qualitytest.info.HdInfo;
import com.yj_app.qualitytest.info.HeadBoyInfo;
import com.yj_app.qualitytest.info.QLineInfo;
import com.yj_app.qualitytest.info.QScoreInfo;
import com.yj_app.qualitytest.info.QrelationshipInfo;
import com.yj_app.qualitytest.info.TeamInfo;
import com.yj_app.qualitytest.info.WorkSpaceInfo;
import com.yj_app.qualitytest.util.DateUtils;

import org.litepal.LitePal;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class HouDuFragment extends BaseFragment {


    @BindView(R.id.biaozhun_spinner)
    AppCompatSpinner biaozhunSpinner;
    @BindView(R.id.cj_name)
    TextView cjName;
    @BindView(R.id.line_name)
    MaterialAutoCompleteTextView lineName;
    @BindView(R.id.banzu_spinner)
    AppCompatSpinner banzuSpinner;
    @BindView(R.id.zr_name)
    MaterialAutoCompleteTextView zrName;
    @BindView(R.id.hd_number)
    TextView hdtv;

    @BindView(R.id.my_recy)
    RecyclerView myRecy;
    Bundle bundle;
    List<QScoreInfo> qScoreInfos = new ArrayList<>();//检查的项目
    ArrayAdapter<QLineInfo> searchAdapter;

    QLineInfo qLineInfo;//选中的生产线名称
    WorkSpaceInfo workSpaceInfo;//车间信息


    List<HeadBoyInfo> headBoyInfos = new ArrayList<>();//主任数据源
    ArrayAdapter<HeadBoyInfo> searchHeadboyAdapter;//主任适配器
    HeadBoyInfo headBoyInfo;

    TeamInfo teamInfo;//已选择的班组
    int teamSelectPos;//进入页面后班组初始化的pos

    private HDadapter hDadapter;
    List<HdInfo> hdInfoList;//数据源

    public static HouDuFragment getIntance() {
        HouDuFragment houDuFragment = new HouDuFragment();
        return houDuFragment;
    }

    public HouDuFragment setBundle(Bundle bundle) {
        this.bundle = bundle;
        return this;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        if (rootView == null) {
            rootView = View.inflate(getContext(), R.layout.fragment_houdu, null);
        }
        ButterKnife.bind(this, rootView);
        initView();
        initEvent();
        return rootView;
    }

    private void initEvent() {

        hDadapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                HdInfo hdInfo= (HdInfo) adapter.getItem(position);

                new SweetAlertDialog(getContext(), SweetAlertDialog.EDITE_TYPE)
                        .setTitleText("请输入厚度").setEditHint("厚度").setShowKeyBord(true).setEditText(hdInfo.getScore()).setEditGravity(Gravity.CENTER).setConfirmText("确定").setCancelText("取消")
                        .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                            @Override
                            public void onClick(SweetAlertDialog sweetAlertDialog) {
                                if (TextUtils.isEmpty(sweetAlertDialog.getmEditText().trim())) {
                                    baseActivity.toastError("请填写厚度");
                                    return;
                                }
                                /*判断这一次输入的数据是否和数据库中已经存在的数据一样 如果一杨的话 不做存储只是隐藏弹窗*/
                                if (!TextUtils.equals(sweetAlertDialog.getmEditText().trim(),hdInfo.getScore())){
                                    //通过条目查处这条数据在数据库中id 然后用id去更新数据库中的数据
                                    hdInfo.setScore(sweetAlertDialog.getmEditText().trim());
                                    HdInfo hdInfoSearch= (HdInfo) LitePal.where("hdinfo.itemname = ?",hdInfo.getItemname()).findFirst(HdInfo.class);
                                    hdInfoSearch.setScore(sweetAlertDialog.getmEditText().trim());
                                    hdInfoSearch.update(hdInfoSearch.getId());
                                    hDadapter.notifyItemChanged(position);
                                }
                                sweetAlertDialog.dismiss();

                            }
                        }).setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                        sweetAlertDialog.dismiss();
                    }
                }).show();
            }
        });


        lineName.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
                qLineInfo = (QLineInfo) adapterView.getItemAtPosition(position);
                workSpaceInfo = LitePal.where("cjcode = ?", qLineInfo.getCjcode()).findFirst(WorkSpaceInfo.class);
                cjName.setText(workSpaceInfo != null ? workSpaceInfo.getCjname() : "无法获取");
                if (workSpaceInfo != null) {
                    //班组和车间不为空
                    //设置主任
                    if (workSpaceInfo != null && banzuSpinner.getSelectedItem() != null) {
                        TeamInfo teamInfo = (TeamInfo) banzuSpinner.getSelectedItem();
                        QrelationshipInfo qrelationshipInfo = LitePal.where("cjcode = ? and cteam = ?", workSpaceInfo.getCjcode(), teamInfo.getGname()).findFirst(QrelationshipInfo.class);
                        if (qrelationshipInfo == null) {
                            qrelationshipInfo = LitePal.where("cjcode = ? and cteam = ?", qLineInfo.getScxcode(), teamInfo.getGname()).findFirst(QrelationshipInfo.class);
                        }
                        if (qrelationshipInfo != null) {
                            headBoyInfo = new HeadBoyInfo();
                            headBoyInfo.setNickname(qrelationshipInfo.getNICKNAME());
                            headBoyInfo.setUsercode(qrelationshipInfo.getUSERCODE());
                            zrName.setText(qrelationshipInfo.getNICKNAME());
                        }
                    }
                }
            }
        });
        zrName.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                headBoyInfo = (HeadBoyInfo) parent.getItemAtPosition(position);


            }
        });

    }

    private void initView() {
        initcheckBzlxAdapter();
        initScLineAdapter();
        initTeam();
        initZrAdapter();
        initHdAdapter();

    }

    private void initHdAdapter() {
        hdInfoList = LitePal.findAll(HdInfo.class);
        hDadapter = new HDadapter(R.layout.item_hd, hdInfoList);
        myRecy.setLayoutManager(new LinearLayoutManager(getContext()));
        myRecy.setAdapter(hDadapter);

    }

    /*获取包装的类型 如“纸包 扎把”的数据 并装入适配器*/
    private void initcheckBzlxAdapter() {
        qScoreInfos = LitePal.where("qscoreinfo.ccode LIKE ? ", bundle.getString(Config.P_ID) + "05%").find(QScoreInfo.class);
        ArrayAdapter<QScoreInfo> adapter_class = new ArrayAdapter(getContext(), R.layout.simple_list_item_1, qScoreInfos);
        biaozhunSpinner.setAdapter(adapter_class);
    }

    /*初始化生产线*/
    private void initScLineAdapter() {
        List<QLineInfo> qLineInfos = LitePal.findAll(QLineInfo.class);
        searchAdapter = new ArrayAdapter(getContext(), R.layout.simple_list_item_1, qLineInfos);
        lineName.setAdapter(searchAdapter);
        //我想在控件准备输入时直接弹出 所以设置了onFocusChange事件
        showDropDown(lineName);
    }

    /*班组的初始化*/
    private void initTeam() {
        teamInfo = (TeamInfo) bundle.getSerializable(Config.TEAM_INFO);
        teamSelectPos = bundle.getInt(Config.TEAM_POSTION);
        List<TeamInfo> teamInfoList = LitePal.findAll(TeamInfo.class);
        ArrayAdapter<TeamInfo> teamInfoArrayAdapter = new ArrayAdapter<TeamInfo>(getContext(), R.layout.simple_list_item_1, teamInfoList);
        banzuSpinner.setAdapter(teamInfoArrayAdapter);
        banzuSpinner.setSelection(teamSelectPos);
    }

    /*主任的初始化*/
    private void initZrAdapter() {
        List<HeadBoyInfo> headBoyInfos = LitePal.findAll(HeadBoyInfo.class);
        searchHeadboyAdapter = new ArrayAdapter(getContext(), R.layout.simple_list_item_1, headBoyInfos);
        zrName.setAdapter(searchHeadboyAdapter);
        showDropDown(zrName);
    }


    @OnClick(R.id.hd_number)
    public void onViewClicked() {

        if (null == qLineInfo && null == headBoyInfo) {
            baseActivity.toastError("请先选择生产线或者车间主任");
            return;
        }

        new SweetAlertDialog(getContext(), SweetAlertDialog.EDITE_TYPE)
                .setTitleText("请输入厚度").setEditHint("厚度").setShowKeyBord(true).setEditGravity(Gravity.CENTER).setConfirmText("确定").setCancelText("取消")
                .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                        if (TextUtils.isEmpty(sweetAlertDialog.getmEditText().trim())) {
                            baseActivity.toastError("请填写厚度");
                            return;
                        }

                        save(sweetAlertDialog.getmEditText().trim());
                        sweetAlertDialog.dismiss();

                    }
                }).setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
            @Override
            public void onClick(SweetAlertDialog sweetAlertDialog) {
                sweetAlertDialog.dismiss();
            }
        }).show();


    }

    private void save(String hdNumber) {

        HdInfo hdInfo = new HdInfo();
        QScoreInfo qScoreInfo = (QScoreInfo) biaozhunSpinner.getSelectedItem();
        hdInfo.setqScoreInfoId(qScoreInfo.getItemid());
        hdInfo.setItemname(qScoreInfo.getItemname());

        hdInfo.setCjcode(workSpaceInfo.getCjcode());
        hdInfo.setCjname(workSpaceInfo.getCjname());

        hdInfo.setqLineId(qLineInfo.getScxcode());
        hdInfo.setScxname(qLineInfo.getScxname());
        teamInfo = (TeamInfo) banzuSpinner.getSelectedItem();
        hdInfo.setGcode(teamInfo.getGcode());

        hdInfo.setUsercode(headBoyInfo.getUsercode());
        hdInfo.setNickname(headBoyInfo.getNickname());

        hdInfo.setScore(hdNumber);
        hdInfo.setTime(DateUtils.convertToString(System.currentTimeMillis(),
                DateUtils.TIME_FORMAT));
        hdInfo.save();
        hdtv.setText(hdNumber);
        hdInfoList.add(0,hdInfo);
        hDadapter.setNewData(hdInfoList);

    }
}
